package com.yyk.yiliao.ui.gongyong.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.bean.JsonBean;
import com.yyk.yiliao.listener.DialogSureCancelListenter;
import com.yyk.yiliao.listener.ToolbarListenter;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.util.DialogUtil;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.bean.UseraddressDel_Info;
import com.yyk.yiliao.bean.UseraddressEditInfo_Info;
import com.yyk.yiliao.bean.UseraddressEdit_Info;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import ch.ielse.view.SwitchView;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 管理收获地址  编辑删除
 */
public class EditerAdress_Activity extends BaseActivity {

    @BindView(R.id.et_szdq) //地址
            TextView etSzdq;
    @BindView(R.id.bt_save) //保存
            Button btSave;
    @BindView(R.id.tv_name)// 名字
            EditText tvName;
    @BindView(R.id.tv_province)// 省市级
            TextView tvProvince;

    @BindView(R.id.tv_phone)
    EditText tvPhone;
    @BindView(R.id.switchView)
    SwitchView switchView;

    private OptionsPickerView pvOptions;
    private int province_id;
    private String county_id;
    private String city_id;
    private String id;

    @Override
    public int getLayoutId() {
        return R.layout.activity_editer_adress;
    }

    @Override
    public void initView() {
        initToobar();

    }

    private void initToobar() {
        setBackArrow();
        setTitle("管理收货地址");
        setMainTitleRightText("删除", new ToolbarListenter() {
            @Override
            public void onClickListenter() {


                DialogUtil.getIntanse().showReturnTips(mActivity, null, "是否删除此地址", "删除", "放弃", new DialogSureCancelListenter() {
                    @Override
                    public void onSureListenter() {
                        delAddress();

                    }

                    @Override
                    public void onCancelListenter() {

                    }
                }, false);

            }
        });
    }

    @Override
    public void initData() {
        initGetIntent();
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        initAddress();
    }

    private void initGetIntent() {
        if (getBundle() != null) {
            id = getBundle().getString("id");
        }
    }


    @OnClick({R.id.tv_province, R.id.bt_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_province:
                mHandler.sendEmptyMessage(MSG_LOAD_DATA);
                if (isLoaded) {
                    showPickerView();
                } else {
//                    Toast.makeText(EditerAdress_Activity.this, "Please waiting until the data is parsed", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.bt_save:
                String name = tvName.getText().toString().trim();
                String address = etSzdq.getText().toString().trim();
                String phone = tvPhone.getText().toString().trim();
                String province = tvProvince.getText().toString().trim();

                if (TextUtils.isEmpty(name)) {
                    ToastUtil.showShort(this, "请填写姓名");
                    return;
                }

                if (TextUtils.isEmpty(phone)) {
                    ToastUtil.showShort(this, "请输入正确手机号码");
                    return;
                }
                if (TextUtils.isEmpty(province)) {
                    ToastUtil.showShort(this, "请选择详细地址");
                    return;
                }

                if (TextUtils.isEmpty(address)) {
                    ToastUtil.showShort(this, "请选择所在地区");
                    return;
                }
                int switchv;
                if (switchView.isOpened()) {
                    switchv = 2;
                } else {
                    switchv = 1;
                }
                Map<String, String> map = new TreeMap<>();
                map.put("uid", Hawk.get("uid", 0) + "");
                map.put("id", id);
                map.put("name", name);
                map.put("phone", phone);
                map.put("address", address);
                map.put("province", String.valueOf(province_id));
                map.put("city", city_id);
                map.put("county", county_id);
                map.put("status", String.valueOf(switchv));
                map.put("sign", Md5Util2.createSign(map));
                DialogUtil.getIntanse().showReturnTips(mActivity, null, "是否保存本次编辑结果", "保存", "不保存", new DialogSureCancelListenter() {
                    @Override
                    public void onSureListenter() {
                        editAdress(map);

                    }

                    @Override
                    public void onCancelListenter() {

                    }
                }, false);
                break;


        }
    }

    /**
     * 删除某个地址
     *
     */
    private void delAddress() {
        Map<String, String> map = new TreeMap<>();
        map.put("id", id);
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postUseraddressDel(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<UseraddressDel_Info>() {

                    @Override
                    public void onCompleted() {
                        //完成的时候调用
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        //失败的时候调用-----一下可以忽略 直接 callBack.onFaild("请求失败");
                    }

                    @Override
                    public void onNext(UseraddressDel_Info info) {
                        if (info.getCode() == 1) {
                            ToastUtil.showShort(EditerAdress_Activity.this, info.getMsg());
                            finish();
                        }
                    }
                });
        try {
            //因为网络请求在子线程，所以不能让宿主线程过早的结束。
            Thread.sleep(100);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
    }

    /**
     * 编辑某个地址
     *
     * @param map
     */
    private void editAdress(Map<String, String> map) {
        RxUtils.getInstance().retrofit.create(ApiService.class).postUseraddressEdit(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<UseraddressEdit_Info>() {

                    @Override
                    public void onCompleted() {
                        //完成的时候调用
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        //失败的时候调用-----一下可以忽略 直接 callBack.onFaild("请求失败");


                    }

                    @Override
                    public void onNext(UseraddressEdit_Info info) {
                        if (info.getCode() == 1) {
                            ToastUtil.showShort(EditerAdress_Activity.this, info.getMsg());
                            finish();
                        }
                    }


                });
        try {
            //因为网络请求在子线程，所以不能让宿主线程过早的结束。
            Thread.sleep(100);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

    }

    /**
     * 获取地址的详细信息
     */
    private void initAddress() {
        Map<String, String> map = new TreeMap<>();

        map.put("id", id);
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postUseraddressEditInfo(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<UseraddressEditInfo_Info>() {

                    @Override
                    public void onCompleted() {
                        //完成的时候调用
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        //失败的时候调用-----一下可以忽略 直接 callBack.onFaild("请求失败");
                    }

                    @Override
                    public void onNext(UseraddressEditInfo_Info info) {
                        Logger.e("编辑地址" + info.toString());
                        if (info.getCode() == 1) {
                            UseraddressEditInfo_Info.DataBean data = info.getData();
                            tvName.setText(data.getName());
                            //TODO 因为这个int 类型所以没有再往下走
                            tvPhone.setText(data.getPhone() + "");
                            tvProvince.setText(data.getProvince_name() + " " + data.getCity_name() + " " + data.getCounty_name());
                            etSzdq.setText(data.getAddress());
                            if (data.getStatus() == 2) {
                                switchView.setOpened(true);
                            } else {
                                switchView.setOpened(false);
                            }


                            province_id = data.getProvince();
                            city_id = String.valueOf(data.getCity());
                            county_id = String.valueOf(data.getCounty());
                            id = String.valueOf(data.getId());
                        } else {
                        }
                    }


                });
        try {
            //因为网络请求在子线程，所以不能让宿主线程过早的结束。
            Thread.sleep(100);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

    }



    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private ArrayList<JsonBean> index1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> index2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> index3Items = new ArrayList<>();

    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    private boolean isLoaded = false;


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

//                        Toast.makeText(AddAdress_Activity.this, "Begin Parse Data", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
//                    Toast.makeText(AddAdress_Activity.this, "Parse Succeed", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
//                    Toast.makeText(AddAdress_Activity.this, "Parse Failed", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    private void showPickerView() {// 弹出选择器
        pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {


            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() + "  " +
                        options2Items.get(options1).get(options2) + "  " +
                        options3Items.get(options1).get(options2).get(options3);
                tvProvince.setText(tx);
                province_id = index1Items.get(options1).getName_id();
                city_id = index2Items.get(options1).get(options2);
                county_id = index3Items.get(options1).get(options2).get(options3);


//                String tx2 = index1Items.get(options1).getName_id() + "  " +
//                        index2Items.get(options1).get(options2) + "  " +
//                        index3Items.get(options1).get(options2).get(options3);
//                Toast.makeText(AddAdress_Activity.this, tx2, Toast.LENGTH_SHORT).show();


            }
        })
                .setTitleText("")
                .setSubmitText("确定")//确定按钮文字
                .setSubCalSize(13)
                .setSubmitColor(0xff212121)
                .setCancelText("取消 ")//取消按钮文字
                .setSubCalSize(13)
                .setCancelColor(0xff212121)
                .setDividerColor(0xffE6E6E6)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(15)
                .isDialog(false)//是否显示为对话框样式
                .setLineSpacingMultiplier(2.5f)
                .setSelectOptions(14, 1, 1)  //设置默认选中项
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    public String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = getJson(this, "provincezk.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;
        index1Items = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            // 这里是显示 在UI 上的参数
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            //下面是 需要调用的ID 参数
            ArrayList<String> CityID = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaID = new ArrayList<>();//该省的所有地区列表（第

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                // 城市 name add
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                // 城市 ID  add
                String cityid = String.valueOf(jsonBean.get(i).getCityList().get(c).getName_id());
                CityID.add(cityid);
                // 地区 name
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表
                // 地区 ID
                ArrayList<String> City_AreaID = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                    City_AreaID.add("");
                } else {
                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        // 地区 name add
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);
                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                        // 地区 id add
                        String AreaID = jsonBean.get(i).getCityList().get(c).getArea_id().get(d);
                        City_AreaID.add(AreaID);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
                Province_AreaID.add(City_AreaID);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);
            index2Items.add(CityID);
            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
            index3Items.add(Province_AreaID);
        }


        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    /**
     * <P>使用gson 解析</P>
     *
     * @param result
     * @return
     */
    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            //含ID 的解析
            Gson gson = new Gson();
            ArrayList<JsonBean> jsonBeen = gson.fromJson(result, new TypeToken<ArrayList<JsonBean>>() {
            }.getType());
            detail = jsonBeen;

        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        EventBus.getDefault().unregister(this);

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (pvOptions != null && pvOptions.isShowing()) {//对象不为空且已经显示
                pvOptions.dismiss();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }


}
